<template>
  <el-form
    ref="dynamicForm"
    class="dynamic-from"
    label-position="right"
    :rules="rulesForm"
    :model="form"
    label-width="120px"
  >
    <template v-if="fromData.length">
      <!-- 固定字段 -->
      <template v-if="isFixedField">
        <el-form-item
          label="描述："
          prop="description"
          :rules="[
            { required: true, message: '请输入描述', trigger: 'blur' },
          ]"
        >
          <el-input
            v-model="form.description"
            :disabled="isEdit"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="单位："
          prop="unit"
          :rules="[
            { required: true, message: '请选择单位', trigger: 'blur' },
          ]"
        >
          <el-select
            v-model="form.unit"
            :disabled="isEdit"
          >
            <el-option
              v-for="(item, k) in unitList"
              :key="k"
              :label="item.name"
              :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
      </template>
      <!-- 动态字段 -->
      <el-form-item
        v-for="(item, k) in fromData"
        :key="k"
        :label="item.label + '：'"
        :prop="item.name"
        :class="item.isRows ? 'from-rows': ''"
      >
        <template v-if="item.type === 'input'">
          <el-input
            v-model="form[item.name]"
            :type="item.props.type"
            :autosize="item.props.autosize"
            :clearable="item.props.clearable"
            :placeholder="item.props.placeholder"
            :disabled="isEdit"
            :maxlength="item.props.maxlength"
          ></el-input>
        </template>
        <template v-if="item.type === 'number'">
          <el-input
            v-model="form[item.name]"
            type="input"
            :autosize="item.props.autosize"
            :clearable="item.props.clearable"
            :placeholder="item.props.placeholder"
            :disabled="isEdit"
            :maxlength="item.props.maxlength"
            @keyup.native="numberFilter(item.name)"
          ></el-input>
        </template>
        <template v-if="item.type === 'select'">
          <el-select
            v-model="form[item.name]"
            :placeholder="item.props.placeholder"
            :clearable="item.props.clearable"
            :disabled="isEdit"
          >
            <el-option
              v-for="(childItem, child_k) in item.options"
              :key="child_k"
              :label="childItem.name"
              :value="childItem.code"
            ></el-option>
          </el-select>
        </template>
        <template v-if="item.type === 'date'">
          <el-date-picker
            v-model="form[item.name]"
            :type="item.props.type"
            :placeholder="item.props.placeholder"
            :value-format="item.props.valueFormat"
            :disabled="isEdit"
          >
          </el-date-picker>
        </template>
      </el-form-item>

    </template>

  </el-form>
</template>

<script>
import {
  postQueryListSelectData
} from '@/api/frontPage/document/index'
export default {
  name: 'DynamicFrom',
  props: {
    fromData: {
      type: Array,
      require: true,
      default: () => []
    },
    isEdit: {
      type: Boolean,
      default: true
    },
    // 固定字段值
    fixedFieldVal: {
      type: Object,
      default: () => {}
    },
    // 是否展示固定字段
    isFixedField: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        description: this.fixedFieldVal.description,
        unit: this.fixedFieldVal.unit
      },
      rulesForm: {},
      unitList: []
    }
  },
  watch: {
    fromData: {
      handler(newName, oldName) {
        this.initFrom()
      },
      immediate: true,
      deep: true
    },
    fixedFieldVal: {
      handler(newVal, oldVal) {
        this.form.description = newVal.description
        this.form.unit = newVal.unit
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    if (this.isFixedField) {
      this.getCodeSelect()
    }
  },
  methods: {
    initFrom() {
      const fromData = this.fromData
      const form = {
        description: this.fixedFieldVal.description,
        unit: this.fixedFieldVal.unit
      }
      const rulesForm = {}
      fromData.forEach((item, k) => {
        form[item.name] = item.value
        if (item.validate && item.validate.length) {
          rulesForm[item.name] = item.validate
        }
      })
      this.form = form
      this.rulesForm = rulesForm
    },
    numberFilter(name) {
      this.$nextTick(() => {
        let val = JSON.parse(JSON.stringify(this.form[name]))
        val = val.replace(/[^\d.]/g, '') // 先把非数字的都替换掉，除了数字和.
        val = val.replace(/^\./g, '') // 必须保证第一个为数字而不是.
        val = val.replace(/\.{2,}/g, '.') // 保证只有出现一个.而没有多个.
        val = val.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.') // 保证.只出现一次，而不能出现两次以上
        if (val.split('')[0] === '0') {
          if (val.split('')[1] !== '.' && val.split('').length > 1) {
            const arr = val.split('')
            arr.splice(1, 1)
            val = arr.join('')
          }
        }
        this.form[name] = val
      })
    },
    // 根据列表code获取列表值的下拉数据
    async getCodeSelect() {
      const val = await postQueryListSelectData('unit')
      this.unitList = val.result
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
// @import "~@/assets/styles/variables";
::v-deep .el-form-item__label {
  line-height: 32px;
  padding: 0;
  text-align: right;
}
::v-deep .el-radio {
  line-height: 32px;
}
::v-deep label {
  margin: 0 20px 0 0;
}

::v-deep .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label {
  &:after {
    content: "";
    margin-left: 0px;
  }
  &:before {
    content: "*";
    color: #f46a6a;
    margin-right: 4px;
  }
}
::v-deep .el-date-editor.el-input {
  width: 100%;
}
::v-deep .el-textarea.is-disabled {
  padding-top: 7px;
}
.dynamic-from {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-column-gap: 60px;
  .from-rows {
    grid-column-start: 1;
    grid-column-end: 3;
  }
}
</style>
